package com.example.codediff.controller;

import com.example.codediff.model.CompareResult;
import com.example.codediff.model.CallChainResult;
import com.example.codediff.service.JarCompareService;
import com.example.codediff.service.JarCallChainService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * JAR包比对控制器
 * 处理前端页面请求和文件上传
 */
@Controller
public class JarCompareController {

    private static final Logger log = LoggerFactory.getLogger(JarCompareController.class);

    @Autowired
    private JarCompareService jarCompareService;

    @Autowired
    private JarCallChainService jarCallChainService;

    /**
     * 首页请求处理
     * @return 返回index模板页面
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 处理JAR包比对请求
     * @param oldJar 旧版本JAR文件
     * @param newJar 新版本JAR文件
     * @param packagePrefix 包前缀（用于过滤需要比对的类）
     * @return 比对结果
     */
    @PostMapping("/compare")
    @ResponseBody
    public CompareResult compareJars(@RequestParam("oldJar") MultipartFile oldJar,
                                   @RequestParam("newJar") MultipartFile newJar,
                                   @RequestParam(value = "packagePrefix", defaultValue = "") String packagePrefix) {
        try {
            return jarCompareService.compareJars(oldJar, newJar, packagePrefix);
        } catch (Exception e) {
            log.error("比对JAR文件失败", e);
            throw new RuntimeException("比对JAR文件失败: " + e.getMessage(), e);
        }
    }

    /**
     * 处理JAR包比对请求，包含调用链分析
     */
    @PostMapping("/compareWithCallChain")
    @ResponseBody
    public CallChainResult compareWithCallChain(
            @RequestParam("oldJarFile") MultipartFile oldJarFile,
            @RequestParam("newJarFile") MultipartFile newJarFile,
            @RequestParam("changedMethod") String changedMethod) {
        
        log.info("接收调用链分析请求: oldJar={}, newJar={}, changedMethod={}", 
                oldJarFile.getOriginalFilename(), 
                newJarFile.getOriginalFilename(),
                changedMethod);
        
        return jarCallChainService.analyze(oldJarFile, newJarFile, changedMethod);
    }
}
